package com.Qinmeiwei.web.util.tag;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.Qinmeiwei.web.util.Constants;

public abstract class ResourceTag extends SimpleTagSupport {
	
	/** 加载的JS或CSS名称，多个用逗号隔开*/
	protected String src;

	protected final Set<String> pageResourceSet = new LinkedHashSet<String>();
	
	public void doTag() throws JspException, IOException {
		if(getSrc() != null && getSrc().length() > 0){
			String srcs[] = getSrc().split(",");
			for(String s : srcs){
				if(!isImported(s)){
					pageResourceSet.add(s);
				}
			}
			if(!pageResourceSet.isEmpty()){
				String element = create();
				this.getJspContext().getOut().write(element);
			}
		}else{
			throw new JspException("The attribute src is empty!");
		}
	}
	
	abstract protected String create();
	
	protected boolean isImported(String jsName){
		Object value = this.getJspContext().getAttribute(jsName);
		if(value != null){
			return true;
		}else{
			this.getJspContext().setAttribute(jsName, true);
			return false;
		}
	}
	
	public boolean isDebug(){
		return Constants.getInstance().isDebugMode;
	}
	
	public String getSrc() {
		return src;
	}

	public void setSrc(String src) {
		this.src = src;
	}
}
